/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminFrame.java
 *
 * Created on 24.nov.2011, 09:42:14
 */
package no.uials.distsys;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Martinsen
 */
public class AdminFrame extends javax.swing.JFrame {
    private Login login;
    private AdminService service;
    private User user;
    private Point p;
    private ArrayList<Article> search = new ArrayList<>();
    private DecimalFormat df;
    private DefaultTableModel articleTableModel = new DefaultTableModel(new String[] {"ID", "Name", "Price", "Stock", "Position"}, 0) {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    
    private DefaultTableModel orderTableModel = new DefaultTableModel(new String[] {"#", "User", "Articles", "Price", "Date"}, 0) {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    
    /** Creates new form AdminFrame */
    public AdminFrame(Login login, AdminService service, User user) throws RemoteException {
        this.login = login;
        this.service = service;
        this.user = user;
        p = null;
        df = new DecimalFormat("¤ #,##0.00");
        initComponents();
        initTables();
        userLabel.setText("Logged on as " + this.user.getName());
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        //Setting location of login box to center of the screen
        setLocation((d.width - this.getWidth())/2, (d.height - this.getHeight())/2);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchField = new javax.swing.JTextField();
        addButton = new javax.swing.JButton();
        changeButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        orderTable = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        articleTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        userLabel = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        optionsMenu = new javax.swing.JMenu();
        changePwMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        logOutMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        aboutMenu = new javax.swing.JMenu();
        infoMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Admin Service");

        searchField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                searchFieldKeyReleased(evt);
            }
        });

        addButton.setText("Add article");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        changeButton.setText("Change article");
        changeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeButtonActionPerformed(evt);
            }
        });

        deleteButton.setText("Delete article");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        orderTable.setModel(orderTableModel);
        jScrollPane1.setViewportView(orderTable);

        articleTable.setModel(articleTableModel);
        articleTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                articleTableMouseReleased(evt);
            }
        });
        jScrollPane2.setViewportView(articleTable);

        jLabel1.setText("Orders");

        userLabel.setText("Logged in as ");

        optionsMenu.setText("Options");

        changePwMenuItem.setText("Change Password");
        optionsMenu.add(changePwMenuItem);
        optionsMenu.add(jSeparator1);

        logOutMenuItem.setText("Log Out");
        logOutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logOutMenuItemActionPerformed(evt);
            }
        });
        optionsMenu.add(logOutMenuItem);

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        optionsMenu.add(exitMenuItem);

        jMenuBar1.add(optionsMenu);

        aboutMenu.setText("About");

        infoMenuItem.setText("Info");
        infoMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                infoMenuItemActionPerformed(evt);
            }
        });
        aboutMenu.add(infoMenuItem);

        jMenuBar1.add(aboutMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(changeButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(deleteButton))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 307, Short.MAX_VALUE)
                        .addComponent(userLabel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(userLabel))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(changeButton)
                    .addComponent(deleteButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
    System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed

private void infoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_infoMenuItemActionPerformed
    JOptionPane.showMessageDialog(null, "Made by Anders Hovland & Ole Martinsen");
}//GEN-LAST:event_infoMenuItemActionPerformed

private void logOutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logOutMenuItemActionPerformed
    login.setVisible(true);
    dispose();
}//GEN-LAST:event_logOutMenuItemActionPerformed

private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchFieldKeyReleased
    search = new ArrayList<>();
    String searchString = searchField.getText().toLowerCase();
    Collection<Article> collection = null;
    
    try {
        collection = service.getArticles().values();
        for (Article article : collection) {
            if (article.getID().toLowerCase().contains(searchString) || article.getName().toLowerCase().contains(searchString)) {
                search.add(article);
            }
        }
        updateArticleTable(search);
    } catch (RemoteException re) {
        System.err.println("*** Connection broken. ***");
    }
}//GEN-LAST:event_searchFieldKeyReleased

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
    new ArticleDialog(this, "Add article", service, false, null).setVisible(true);
    try {
        updateArticleTable(new ArrayList<>(service.getArticles().values()));
    } catch (RemoteException ex) {
        System.err.println("Failed");
    }
}//GEN-LAST:event_addButtonActionPerformed

private void articleTableMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_articleTableMouseReleased
    p = new Point(evt.getPoint());
}//GEN-LAST:event_articleTableMouseReleased

private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeButtonActionPerformed
    if (p != null) {
        try {
            int i = articleTable.rowAtPoint(p);
            p = null;
            String check = (String) articleTableModel.getValueAt(i, 0);
            ArrayList<Article> lines = new ArrayList<>(service.getArticles().values());
            for (Article a : lines) {
                String like = a.getID();
                if (check.equals(like)) {
                    new ArticleDialog(this, "Change article", service, true, a).setVisible(true);
                    try {
                        updateArticleTable(lines);
                    } catch (Exception e) {
                    }
                    break;
                }
            }
        } catch (Exception e) {
        }
    }
}//GEN-LAST:event_changeButtonActionPerformed

private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
    if (p != null) {
        try {
            int i = articleTable.rowAtPoint(p);
            p = null;
            String check = (String) articleTableModel.getValueAt(i, 0);
            ArrayList<Article> lines = new ArrayList<>(service.getArticles().values());
            for (Article a : lines) {
                String like = a.getID();
                if (check.equals(like)) {
                    service.removeArticle(like);
                    updateArticleTable(lines);
                    break;
                }
            }
        } catch (Exception e) {
        }
    }
}//GEN-LAST:event_deleteButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu aboutMenu;
    private javax.swing.JButton addButton;
    private javax.swing.JTable articleTable;
    private javax.swing.JButton changeButton;
    private javax.swing.JMenuItem changePwMenuItem;
    private javax.swing.JButton deleteButton;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenuItem infoMenuItem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JMenuItem logOutMenuItem;
    private javax.swing.JMenu optionsMenu;
    private javax.swing.JTable orderTable;
    private javax.swing.JTextField searchField;
    private javax.swing.JLabel userLabel;
    // End of variables declaration//GEN-END:variables


    private void initTables() throws RemoteException {
        articleTable.getTableHeader().setReorderingAllowed(false);
        articleTable.getTableHeader().setResizingAllowed(false);
        orderTable.getTableHeader().setReorderingAllowed(false);
        orderTable.getTableHeader().setResizingAllowed(false);
        updateArticleTable(new ArrayList<>(service.getArticles().values()));
        updateOrdersTable();
    }
    
    private void updateArticleTable(ArrayList<Article> contents) {
        articleTableModel.setRowCount(0);
        
        for (Article a : contents) {
            String ID = a.getID();
            String name = a.getName();
            String price = df.format(a.getPrice());
            String stock = "" + a.getStock();
            String pos = a.getPosition().toString();
            articleTableModel.addRow(new String[] {ID, name, price, stock, pos});
        }
    }
    
    private void updateOrdersTable() throws RemoteException {
        orderTableModel.setRowCount(0);
        ArrayList<Order> table = new ArrayList<>(service.listOrders().values());
        
        for (Order o : table) {
            String ID = "" + o.getOrderID();
            String name = o.getUser().getName();
            String units = o.getUnits() + "";
            String total = df.format(o.getTotal());
            String date = o.getDateString();
            orderTableModel.addRow(new String[] {ID, name, units, total, date});
        }
    }
}